import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Redirect } from 'react-router-dom';
import * as actionCreators from './store/actionCreators';
import { Row, Col, Form, Input, Button, Checkbox, Icon, message } from 'antd';
import logoImg from '../../assets/images/logo-ant.svg';
import './index.scss';

const FormItem = Form.Item;

class Login extends Component {

  render() {
    const { loginStatus, autoLogin, handleSubmit, form } = this.props;
    if(loginStatus && autoLogin) {
      return <Redirect to='/' />
    } else {
      const { getFieldDecorator } = form;
      return (
        <div className='login-wrapper'>
          <Row>
            <Col className='login-title'>
              <img src={logoImg} alt='this is logo' /> MarkTang Blog
            </Col>
          </Row>
          <Row>
            <Col className='login-form'>
              <Form onSubmit={handleSubmit.bind(this)}>
                <FormItem>
                  {getFieldDecorator('userName', {
                    rules: [{ required: true, message: '用户名必填!'}],
                  })(
                    <Input prefix={<Icon type='user' style={{ color: 'rgba(0,0,0,.25)'}} />} placeholder='用户名' />
                  )}
                </FormItem>
                <FormItem>
                  {getFieldDecorator('password', {
                    rules: [{ required: true, message: '密码必填!'}],
                  })(
                    <Input prefix={<Icon type='lock' style={{ color: 'rgba(0,0,0,.25)'}} />} type='password' placeholder='密码' />
                  )}
                </FormItem>
                <FormItem>
                  {getFieldDecorator('autoLogin', {
                    valuePropName: 'checked',
                    initialValue: false,
                  })(
                    <Checkbox>自动登录</Checkbox>
                  )}
                  <Button type="primary" htmlType="submit" className="login-form-button">
                    登 录
                  </Button>
                </FormItem>
              </Form>
            </Col>
          </Row>
        </div>
      );
    }
  }

}

const mapState = (state) => ({
  loginStatus: state.getIn(['login', 'loginStatus']),
  autoLogin: state.getIn(['login', 'autoLogin'])
});

const mapDispatch = (dispatch) => ({
  handleSubmit(e) {
    e.preventDefault();
    let _this = this;
    _this.props.form.validateFields((err, data) => {
      if (!err) {
        if (data.userName === 'MarkTang' && data.password === '123456') {
          dispatch(actionCreators.changeLoginStatus(true));
          message.success('登录成功');
          setTimeout(() => {
            _this.props.history.push('/home');
          }, 1000);
        } else {
          message.error('登录失败');
          dispatch(actionCreators.changeLoginStatus(false));
        }
      }
    });
  }
});

const WrappedNormalLoginForm = Form.create()(Login);
export default connect(mapState, mapDispatch)(WrappedNormalLoginForm);